let Order = require('../../moudles/accessdb/dao/orderQuery')
let Room = require('../../moudles/accessdb/dao/roomQueryAll')
const {sequelize} = require("../../moudles/accessdb/dao/common/dbconnection");

/**
 * 查看所有的房型 这里调用数据库
 * @returns {Promise<unknown>}
 */
async function handleRequest(page, limit) {
    const offset = (page - 1) * limit;
    return new Promise(async (resolve, reject) => {
        let i = await Order.count();
        Order.findAll({
            limit: limit,
            offset: page
        }).then((res) => {
            let newobj = {
                list: res,
                total: i
            }
            // console.log('res',res)
            resolve(newobj)
        }).catch((e) => {
            reject(e);
        });

    });
}


/**
 * 事务增加订单删除住宅
 */
async function handleRequestBuyRoom(value) {
    const t = await sequelize.transaction();
    try {
        const order = await Order.create(
            {
                roomid: value.roomid,
                userid: value.userid,
                goodnum: value.goodnum,
                address: value.address,
                phone: value.phone,
            },
            {
                logging: console.log,
                transaction: t,
            }
        );

        const roomUpdate = await Room.update(
            { total: sequelize.literal('total-1') },
            {
                where: { roomId: value.roomid },
                transaction: t,
            }
        );

        await t.commit();
        return { order, roomUpdate };
    } catch (error) {
        await t.rollback();
        throw error;
    }
}

// async function handleRequestByQueryRoom(value) {
//     return new Promise(async (resolve, reject) => {
//         Room.findOne(
//             {
//                 where: {roomId: value.roomId}
//             }
//         ).then((res) => {
//             resolve(res)
//         }).catch((e) => {
//             reject(e);
//         })
//     });
// }

module.exports = {handleRequest, handleRequestBuyRoom};